var fs = require('fs')

var dbPath = './db.json'

exports.find = function(callback){
	fs.readFile(dbPath, 'utf8', function(err, data) {
		if (err) {
			return callback(err)
		}
		// 判断是否一开始就是空的
		var students = data ? JSON.parse(data).students : null
		return callback(null, students)
		// console.log(err)
		// console.log(7)
		// console.log(data)
		// console.log(8)
	})
}

exports.save = function(student, callback){
	fs.readFile(dbPath, 'utf8', function(err, data){
		if (err) {
			return callback(err)
		}
		// 判断是否一开始就是空的
		var students = data ? JSON.parse(data).students : [];
		if (students.length <= 0) {
			student.id = 1
		}else{
			student.id = students[students.length - 1].id + 1
		}
		students.push(student)

		var fileData = JSON.stringify({
			students:students
		})

		fs.writeFile(dbPath, fileData, function(err){
			if (err) {
				return callback(err)
			}
			return callback(null)
		});
	})
}

exports.findById = function(id, callback){
	fs.readFile(dbPath, 'utf8', function(err, data){
		if (err) {
			return callback(err)
		}
		var students = JSON.parse(data).students;
		id = parseInt(id);
		var student = students.find(function(item){
			return item.id === id
		})
		callback(null, student)
	})
}

exports.updateById = function(student, callback){
	fs.readFile(dbPath, 'utf8', function(err, data){
		if (err) {
			return callback(err)
		}
		student.id = parseInt(student.id)
		var students = JSON.parse(data).students
		var stu = students.find(function(item){
			return item.id === student.id
		})
		for(var key in student){
			stu[key] = student[key]
		}
		var fileData = JSON.stringify({
			students : students
		})
		fs.writeFile(dbPath, fileData, function(err){
			if (err) {
				return callback(err)
			}
			callback(null)
		})
	})
}

exports.deleteById = function(id, callback){
	fs.readFile(dbPath, 'utf8', function(err, data){
		if (err) {
			return callback(err)
		}
		id = parseInt(id)
		var students = JSON.parse(data).students
		var delIndex = students.findIndex(function(item){
			return item.id === id
		})
		students.splice(delIndex, 1)

		var fileData = JSON.stringify({
			students : students
		})

		fs.writeFile(dbPath, fileData, function(err){
			if (err) {
				return callback(err)
			}
			callback(null)
		})
	})
}